//
//  BDRegisterTableViewController.m
//  BeidouMall
//
//  Created by qie on 16/3/31.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDRegisterTableViewController.h"

@interface BDRegisterTableViewController ()
{
    NSTimer *_timer;
    NSInteger _count;
}
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *accountTextField;
@property (weak, nonatomic) IBOutlet UITextField *verfiyTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwrodTextField;
@property (weak, nonatomic) IBOutlet UITextField *secondpasswrodTextField;

@property (weak, nonatomic) IBOutlet UIButton *getVerifactionButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;

@end

@implementation BDRegisterTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"regisger",nil);
    self.bottomView.height = kScreen_Height - 204;
    
    UITapGestureRecognizer *tap =
    [[UITapGestureRecognizer alloc]  initWithTarget:self action:@selector(dismissMyKeyboard)];
    [self.view addGestureRecognizer:tap];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    CGFloat fontSize = 11.0;
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"en"]) {
        _getVerifactionButton.titleLabel.numberOfLines = 0;
        fontSize = 11.0;
        _getVerifactionButton.titleLabel.font = [UIFont systemFontOfSize:fontSize];
        [_userNameTextField setValue:[UIFont boldSystemFontOfSize:14.0] forKeyPath:@"_placeholderLabel.font"];
        [_accountTextField setValue:[UIFont boldSystemFontOfSize:14.0] forKeyPath:@"_placeholderLabel.font"];
    } else if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zh"]) {
        _getVerifactionButton.titleLabel.numberOfLines = 1;
        fontSize = 14.0;
        _getVerifactionButton.titleLabel.font = [UIFont systemFontOfSize:fontSize];
        [_userNameTextField setValue:[UIFont boldSystemFontOfSize:15.0] forKeyPath:@"_placeholderLabel.font"];
        [_accountTextField setValue:[UIFont boldSystemFontOfSize:15.0] forKeyPath:@"_placeholderLabel.font"];
    } else if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        _getVerifactionButton.titleLabel.numberOfLines = 0;
        fontSize = 9.0;
        _getVerifactionButton.titleLabel.font = [UIFont fontWithName:@"Bzdbt" size:fontSize];
        [_userNameTextField setValue:[UIFont fontWithName:@"Bzdbt" size:10.0] forKeyPath:@"_placeholderLabel.font"];
        [_accountTextField setValue:[UIFont fontWithName:@"Bzdbt" size:10.0] forKeyPath:@"_placeholderLabel.font"];
    }
    
    _registerButton.layer.cornerRadius = 5.0;
    _registerButton.layer.masksToBounds = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

#pragma mark - TextField delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *futrueString = [textField.text changeCharactersInRange:range replacementString:string];
    
    if ([_userNameTextField.text length]
        && [_accountTextField.text length]
        && [_verfiyTextField.text length]
        && [_passwrodTextField.text length]
        && [_secondpasswrodTextField.text length]) {
        _registerButton.enabled = YES;
    } else {
        _registerButton.enabled = NO;
    }
    
    if (textField.tag == 101) {
        if (futrueString.length > kNickNameLength) {
            futrueString = textField.text;
            return NO;
        }
    } else if (textField.tag == 102) {
        if (futrueString.length > kUserNameLength) {
            return NO;
        }
    } else if (textField.tag == 103) {
        if (futrueString.length > kVerificationMaxLength) {
            return NO;
        }
    } else if (textField.tag == 104) {
        if (futrueString.length > kPasswordMaxLength) {
            return NO;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == 101) {
        [_accountTextField becomeFirstResponder];
    } else if (textField.tag == 102) {
        [_verfiyTextField becomeFirstResponder];
    }else if (textField.tag == 103) {
        [_passwrodTextField becomeFirstResponder];
    } else if (textField.tag == 104) {
        [_secondpasswrodTextField becomeFirstResponder];
    } else if (textField.tag == 105) {
        [textField resignFirstResponder];
        [self registerButtonPressed:nil];
    }
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField.tag == 104) {
        _passwrodTextField.text = nil;
        _secondpasswrodTextField.text = nil;
    } else if (textField.tag == 105) {
        if (_secondpasswrodTextField.text.length > 0) {
            _secondpasswrodTextField.text = nil;
        }
    }
    
    //  解决键盘挡住tableView问题
    UIView *view = textField.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    CGRect rect = [cell convertRect:cell.frame toView:self.view];
    if (rect.origin.y / 2 + rect.size.height >= kScreen_Width - 216) {
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 216, 0);
        [self.tableView scrollToRowAtIndexPath:[self.tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
    
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    // 恢复键盘多出的高度
    //    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

-(void)dismissMyKeyboard {// 收起键盘的手势
    [self.view endEditing:YES];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

#pragma mark - Private method

- (void)updateRequestVerifyCodeButton {
    if (--_count > 0) {
        if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zh"]) {
            [_getVerifactionButton setTitle:[NSString stringWithFormat:@"%ld秒后重发",(long)_count] forState:UIControlStateDisabled];
        } else if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"en"]) {
            [_getVerifactionButton setTitle:[NSString stringWithFormat:@"Retrieve in %lds",(long)_count] forState:UIControlStateDisabled];
        }
        
    } else {
        _getVerifactionButton.enabled = YES;
        _getVerifactionButton.backgroundColor = kButtonEnableColor;
        NSString *promit;
        if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zh"]) {
            promit = [NSString stringWithFormat:@"%d秒后重发",kWaitTime];
        } else if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"en"]) {
            promit = [NSString stringWithFormat:@"Retrieve in %ds",kWaitTime];
        }
        [_getVerifactionButton setTitle:promit forState:UIControlStateDisabled];
        [_timer invalidate];
    }
}

#pragma mark - IBActions

- (IBAction)getVerificationButtonPressed:(UIButton *)sender {
    if (_accountTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Account is blank", nil)];
    } else if (!([_accountTextField.text isValidPhoneNum] || [_accountTextField.text isVaildEmail])) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Account format is invalid", nil)];
    } else {
        
        if (_timer != nil) {
            [_timer invalidate];
        }
        
        NSString *url = [NSString stringWithFormat:@"%@%@",[BDNetworking shareInstance].baseUrl,IsRegister];
        [[BDAccountManagerModel shareInstance] checkUserWithUrl:url
                                                          phone:_accountTextField.text
                                                       userType:BUYER
                                              completionHandler:^(NSError *error) {
                                                  if (error != nil) {
                                                      NSLog(@"验证用户:失败%@",[error localizedDescription]);
                                                      NSString *errorStr = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"check user fail", nil),[error localizedDescription]];
                                                      [MBProgressHUD showToast:self.view withText:errorStr];
                                                      [_timer invalidate];
                                                      dispatch_async(dispatch_get_main_queue(), ^{// 更新UI操作必须在主线程
                                                          sender.enabled = YES;
                                                          sender.backgroundColor = kButtonEnableColor;
                                                          [sender setTitle:NSLocalizedString(@"Send Verification code", nil) forState:UIControlStateNormal];
                                                      });
                                                  } else {
                                                      
                                                      NSString *url = [NSString stringWithFormat:@"%@%@?account=%@&type=%@",[BDNetworking shareInstance].baseUrl,VerifyCode,_accountTextField.text,BUYER_REGISTER];
                                                      [[BDAccountManagerModel shareInstance] getVerifyCodeWithUrl:url  completionHandler:^(NSError *error) {
                                                          if (error != nil) {
                                                              NSLog(@"验证码:失败%@",[error localizedDescription]);
                                                              NSString *errorStr = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"Send Verification code", nil),[error localizedDescription]];
                                                              [MBProgressHUD showToast:self.view withText:errorStr];
                                                              
                                                              [_timer invalidate];
                                                              dispatch_async(dispatch_get_main_queue(), ^{// 更新UI操作必须在主线程
                                                                  sender.enabled = YES;
                                                                  sender.backgroundColor = kButtonEnableColor;
                                                                  [sender setTitle:NSLocalizedString(@"Send Verification code", nil) forState:UIControlStateNormal];
                                                              });
                                                          } else {
                                                              
                                                          }
                                                      }];
                                                  }
                                              }];
        _count = kWaitTime;
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateRequestVerifyCodeButton) userInfo:nil repeats:YES];
        sender.enabled = NO;
        sender.backgroundColor = sender.enabled ? kButtonEnableColor : kButtonDisEnableColor;
    }
    
}

- (IBAction)passwordButtonPressed:(UIButton *)sender {
    sender.selected = !sender.selected;
//    _passwrodTextField.secureTextEntry = !sender.selected;
//    _secondpasswrodTextField.secureTextEntry = !sender.selected;
    if ([_passwrodTextField isFirstResponder]) {
        [_passwrodTextField resignFirstResponder];
    }
    if ([_secondpasswrodTextField isFirstResponder]) {
        [_secondpasswrodTextField resignFirstResponder];
    }
    _passwrodTextField.secureTextEntry = !_passwrodTextField.secureTextEntry;
    _passwrodTextField.font = nil;
    _passwrodTextField.font = [UIFont systemFontOfSize:14];
    _secondpasswrodTextField.secureTextEntry = !_secondpasswrodTextField.secureTextEntry;
    _secondpasswrodTextField.font = nil;
    _secondpasswrodTextField.font = [UIFont systemFontOfSize:14];
}

- (IBAction)registerButtonPressed:(UIButton *)sender {
    if (_userNameTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"User name is blank", nil)];
    } else if (![_userNameTextField.text isValidName]) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"User name format is invalid", nil)];
    } else if (_accountTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Account is blank", nil)];
    } else if (!([_accountTextField.text isValidPhoneNum] ||
                 [_accountTextField.text isVaildEmail])) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Account format is invalid", nil)];
    } else if (_verfiyTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Verification code is blank", nil)];
    } else if (![_verfiyTextField.text isVaildVerificationCode]) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Verification code format is invalid", nil)];
    } else if (_passwrodTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Re-enter password", nil)];
    } else if (![_passwrodTextField.text isValidPassword]) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"password format is invalid", nil)];
    } else if (_secondpasswrodTextField.text.length == 0) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Confirm password is invalid", nil)];
    } else if (![_passwrodTextField.text isEqualToString:_secondpasswrodTextField.text]) {
        [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"Passwords in two times are different", nil)];
    } else {
        if (_userNameTextField.isFirstResponder) {
            [_userNameTextField resignFirstResponder];
        } else if (_accountTextField.isFirstResponder) {
            [_accountTextField resignFirstResponder];
        } else if (_verfiyTextField.isFirstResponder) {
            [_verfiyTextField resignFirstResponder];
        } else if (_passwrodTextField.isFirstResponder) {
            [_passwrodTextField resignFirstResponder];
        } else if (_secondpasswrodTextField.isFirstResponder) {
            [_secondpasswrodTextField resignFirstResponder];
        }
        
        NSString *url = [NSString stringWithFormat:@"%@%@",[BDNetworking shareInstance].baseUrl,Register];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:NSLocalizedString(@"Registering", nil)];
        [[BDAccountManagerModel shareInstance] registerWithWithUrl:url
                                                          username:_userNameTextField.text
                                                             phone:_accountTextField.text
                                                          password:_passwrodTextField.text
                                                        verifyCode:_verfiyTextField.text
                                                          userType:BUYER
                                                 completionHandler:^(NSError *error) {
                                                     if (error != nil) {
                                                         NSLog(@"注册失败%@", [error localizedDescription]);
                                                         hud.labelText = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"Register fail", nil),[error localizedDescription]];
                                                         [hud hideAfterDelay:0.5];
                                                     } else {
                                                         hud.labelText = NSLocalizedString(@"Register successful", nil);
                                                         [hud hideAfterDelay:0.5];
                                                         
                                                         [[BDAccountManagerModel shareInstance] setLogin:YES];
                                                         
                                                         dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC);
                                                         dispatch_after(time, dispatch_get_main_queue(), ^{
                                                             [self dismissViewControllerAnimated:YES completion:nil];
                                                         });
                                                     }
                                                     
                                                     
                                                 }];
    }
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
